from django.contrib.auth.models import User
from django.db import models


# Demo，不用理会
class User(models.Model):
    name = models.CharField(max_length=100, verbose_name='Name')
    gender = models.CharField(max_length=100, verbose_name='Gender')
    age = models.IntegerField(verbose_name='Age')
    is_active = models.BooleanField(default=True, verbose_name='Is Active')

# 不知道是什么表但是不能删，每次删都会出问题
class SysRole(models.Model):
    role_id = models.AutoField(primary_key=True)
    label = models.CharField(max_length=50)
    status = models.BooleanField(default=True)
    creater = models.IntegerField(null=True, blank=True)
    updater = models.IntegerField(null=True, blank=True)
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    delete = models.BooleanField(default=False)


# 用户表
class SysUser(models.Model):
    user_id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=50, unique=True)
    #nickname = models.CharField(max_length=100)
    password = models.CharField(max_length=128)
    email = models.EmailField()
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)
    status = models.BooleanField(default=True)
    creater = models.IntegerField(null=True, blank=True)
    updater = models.IntegerField(null=True, blank=True)
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    delete = models.BooleanField(default=False)

    # 添加 role 字段
    ROLE_CHOICES = [
        ('teacher', '教师'),
        ('student', '学生'),
    ]
    role = models.CharField(max_length=10, choices=ROLE_CHOICES, verbose_name="用户角色")

    # 用户能力字段
    ability = models.PositiveIntegerField(default=0, verbose_name="能力值")
    enthusiasm = models.PositiveIntegerField(default=0, verbose_name="参与积极性")
    communication = models.PositiveIntegerField(default=0, verbose_name="表达能力")
    popularity = models.PositiveIntegerField(default=0, verbose_name="人气值")
    credit = models.PositiveIntegerField(default=0, verbose_name="信用值")
    times = models.PositiveIntegerField(default=0, verbose_name="已完成任务次数")
    attended = models.ManyToManyField('Task', blank=True, related_name='task_attendees', verbose_name="参加过的任务")


# 教师创建的任务
class Task(models.Model):
    title = models.CharField(max_length=100, verbose_name="任务标题")
    description = models.TextField(verbose_name="任务描述")
    min_group_size = models.PositiveIntegerField(verbose_name="最小组员数")
    max_group_size = models.PositiveIntegerField(verbose_name="最大组员数")
    deadline = models.DateTimeField(verbose_name="任务截止日期")
    scoring_criteria = models.TextField(verbose_name="评分标准")
    sample = models.FileField(upload_to="samples/", verbose_name="标准样例", null=True, blank=True)
    status = models.CharField(
        max_length=20,
        choices=[
            ("grouping_up", "学生正在分组"),
            ("task_division", "班级学生正在分配任务"),
            ("working", "学生完成任务中"),
            ("scoring", "学生已完成任务，正在评分中"),
            ("finished", "任务结束"),
        ],
        default="grouping_up",
        verbose_name="任务状态",
    )
    teacher = models.ForeignKey(
        'SysUser',  # 外键关联到 SysUser 表
        on_delete=models.CASCADE,  # 当教师被删除时，删除对应的任务
        verbose_name="教师",
        related_name="teacher_tasks"  # 反向查询时使用的字段名
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    leaders = models.ManyToManyField(
        SysUser,
        limit_choices_to={'role': 'student'},
        related_name="leader_tasks",
        verbose_name="负责任务的学生",
        blank=True,
    )
    students_number = models.PositiveIntegerField(default=0, verbose_name="班级中学生数目")

class Students(models.Model):
    task = models.ForeignKey('Task', on_delete=models.CASCADE, related_name='students', verbose_name="任务")
    user = models.ForeignKey('SysUser', on_delete=models.CASCADE, related_name='student_tasks', verbose_name="用户")

    def __str__(self):
        return f"Students {self.user.username} in Task {self.task.title}"
    #添加Students表与Task模型的关系，一个学生可以加入多个任务，一个任务可以有多个学生

class Subtask(models.Model):
    task = models.ForeignKey(
        Task,
        related_name="subtasks",
        on_delete=models.CASCADE,
        verbose_name="任务"
    )
    created_by = models.ForeignKey(
        SysUser,
        on_delete=models.SET_NULL,
        null=True,
        related_name="created_subtasks",
        verbose_name="创建者"
    )
    assigned_to = models.ForeignKey(
        SysUser,
        on_delete=models.SET_NULL,
        null=True,
        related_name="assigned_subtasks",
        verbose_name="分配给"
    )
    group_id = models.ForeignKey('Group', on_delete=models.CASCADE, related_name='subtasks')
    status = models.CharField(
        max_length=20,
        choices=[('on_time', '按时完成'), ('late', '逾期未交'), ('in_progress', '进行中')],
        default='in_progress'
    )
    start_date = models.DateField(verbose_name="开始日期")
    end_date = models.DateField(verbose_name="结束日期")
    description = models.TextField(verbose_name="子任务描述")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    submitted_file = models.FileField(upload_to="subtask_files/", null=True, blank=True, verbose_name="提交的文件")
    submitted_time = models.DateTimeField(null=True, blank=True, verbose_name="文件提交时间")
    comments = models.TextField(null=True, blank=True, verbose_name="审核评论")

    class Meta:
        verbose_name = "子任务"
        verbose_name_plural = "子任务"

    def __str__(self):
        return f"Subtask for {self.task.title} - Assigned to {self.assigned_to.username}"
# 小组表
class Group(models.Model):
    group_name = models.CharField(max_length=100)
    leader_id = models.ForeignKey(SysUser, on_delete=models.CASCADE)
    group_task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="groups")
    members = models.ManyToManyField(SysUser, related_name="member_groups")

    def __str__(self):
        return f"Group {self.group_name} for task {self.group_task.title}"

class DiscussionComment(models.Model):
    """
    用于存储讨论区的评论
    """
    user = models.ForeignKey(
        SysUser,
        on_delete=models.CASCADE,
        related_name="discussion_comments",
        verbose_name="评论用户"
    )
    group = models.ForeignKey(
        Group,
        on_delete=models.CASCADE,
        related_name="discussion_comments",
        verbose_name="所属小组"
    )
    content = models.TextField(verbose_name="评论内容")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    def __str__(self):
        return f"{self.user.username} 在 {self.group.group_name} 中的评论"

#用于存储组队申请信息
class Application(models.Model):
    task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='applications')
    user = models.ForeignKey(SysUser, on_delete=models.CASCADE, related_name='applications')
    leader = models.ForeignKey(SysUser, on_delete=models.CASCADE, related_name='leader_applications')
    application_text = models.TextField(verbose_name="申请内容")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="申请时间")
    is_read = models.BooleanField(default=False, verbose_name="是否已读")  # 标记是否已读

    class Meta:
        verbose_name = "组队申请"
        verbose_name_plural = "组队申请"

    def __str__(self):
        return f"Application by {self.user.username} for task {self.task.title}"

class Score(models.Model):
    # 建立与 SysUser、Task、Group 的多对多关系
    sysusers = models.ManyToManyField(
        SysUser,
        related_name="scores",
        verbose_name="评分用户"
    )
    tasks = models.ManyToManyField(
        Task,
        related_name="scores",
        verbose_name="任务"
    )
    groups = models.ManyToManyField(
        Group,
        related_name="scores",
        verbose_name="小组"
    )
    # 评分维度，假设分数支持小数，最大值可设置为999.99，根据需求调整
    quality = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="任务质量分")
    engagement = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="参与积极性分")
    negotiate = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="协商分")
    on_time = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="准时完成分")
    rematch_willingness = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="重组意愿分")
    total = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="总分")

    # 新增字段：记录哪些评分人已对这条评分记录进行了评分，防止重复评分
    raters = models.ManyToManyField(
        SysUser,
        related_name="rated_scores",
        verbose_name="已评分人员",
        blank=True,
    )

    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "评分"
        verbose_name_plural = "评分记录"

    def __str__(self):
        return f"Score #{self.id}"


class Appeal(models.Model):
    task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name="appeals", verbose_name="任务")
    group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name="appeals", verbose_name="小组")
    sysuser = models.ForeignKey(SysUser, on_delete=models.CASCADE, related_name="appeals", verbose_name="学生")
    reason = models.TextField(verbose_name="申诉理由")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="申诉时间")
    status = models.CharField(max_length=20, default="pending", verbose_name="申诉状态")

    def __str__(self):
        return f"Appeal #{self.id} by {self.sysuser.username}"


class ReferencePosition(models.Model):
    """
    针对某个任务、某个小组的参考职位列表。
    例如：任务: “演讲比赛”，小组: “第3组”，职位: “PPT制作”，需要人数: 2...
    """
    task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='reference_positions')
    group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='reference_positions')
    title = models.CharField(max_length=100, verbose_name="职位名称")
    needed_count = models.PositiveIntegerField(verbose_name="需要人数")
    description = models.TextField(verbose_name="职位描述")

    # 可添加一个字段，记录用户确认后的人数
    confirmed_count = models.PositiveIntegerField(null=True, blank=True, verbose_name="已确认人数")

    def __str__(self):
        return f"[Task: {self.task.title}, Group: {self.group.group_name}] {self.title}"

class ForumPost(models.Model):
    CATEGORY_CHOICES = [
        ('publish', '发布内容'),
        ('myPosts', '我发布的'),
        ('recruitment', '企业招募'),
        ('experience', '经验分享'),
        ('research', '课题研究'),
        ('teamup', '竞赛组队'),
    ]
    title = models.CharField(max_length=200)
    content = models.TextField()
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES, default='publish')
    author = models.ForeignKey(SysUser, on_delete=models.CASCADE, related_name="forum_posts")
    # 附件字段，可使用 FileField 或 ImageField，具体根据需求
    attachment = models.FileField(upload_to="forum_attachments/", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title